<template>
  <el-dialog title="添加子部门" width="500px" :visible.sync="visible" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="部门名称：" prop="deptName">
        <el-input
          ref="input"
          v-model="form.deptName"
          :maxlength="50"
          placeholder="请输入部门名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="上级部门：">
        {{ form.parentDeptName }}
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex';

  export default {
    data() {
      return {
        visible: false,
        form: {
          deptName: '',
          parentDeptName: '',
        },
        rules: {
          deptName: [{ required: true, message: '请输入部门名称', trigger: 'change' }],
        },
      };
    },
    computed: {
      ...mapGetters('user', ['userInfo']),
      organizationId() {
        return this.userInfo.organId;
      },
    },
    methods: {
      onOpen(data) {
        const { id, deptName } = data;
        this.form = { parentDeptName: deptName, parentId: id, deptName: '' };
        this.visible = true;

        this.$nextTick(() => {
          this.$refs['input'].focus();
        });
      },
      close() {
        this.$refs['form'].resetFields();
        this.visible = false;
      },
      async save() {
        this.$refs['form'].validate(async valid => {
          if (valid) {
            const { status, message } = await this.$store.dispatch('organization/addTreeNode', {
              ...this.form,
              organizationId: this.organizationId,
            });
            this.close();
            if (status === 999) {
              this.$parent.$parent.$parent.$parent.$refs['orgMain'].onNoAuth(message);
            }
          }
        });
      },
    },
  };
</script>
